package com.shop.cart.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.base.common.entity.User;
import com.base.common.entity.bean.Cart;
import com.base.common.http.HttpResult;
import com.base.common.http.HttpStatus;
import com.base.common.utils.CookieUtils;
import com.shop.cart.service.CartService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.List;

/**
 * 功能描述：购物车
 */
@RestController
@RequestMapping("/cart")
public class CartController {


    /**
     * 功能描述：注入购物车service对象
     */
    @Autowired
    private CartService cartService;

    /**
     * 需求：添加购物车
     * 请求：/addcart
     * 参数：map
     * 返回值：JmypResult
     * 1）查询购物车列表
     * 2）判断购物车列表中是否存在相同的商品
     * 3）如果存在相同的商品，此商品数量相加
     * 4）否则，直接把商品添加到购物车中即可
     */
    /**
     * 需求：添加购物车数据
     * 请求：http://localhost:8086/cart/addGoodsToCartList/1369377/1
     * 参数：Long itemId,Integer num
     * 返回值:PygResult
     * 业务思路：
     * 1，从request中获取用户身份信息
     * 2，查询购物车列表数据
     * 3，添加购物车数据（把新的数据添加到原来的购物车列表中）
     * 4，判断用户是否处于登录状态
     * 5，登录，把购物车列表添加到redis购物车
     * 6，否则没有登录，把购物车列表添加到cookie购物车
     * 购物车列表数据结构：
     * 思路：用户可以购买多个商家的多个商品
     * 1，购物车中有多个商家
     * 2，每一个商家可能具有多个商品
     * List<商家（购物商品集合）>
     * List<Cart>
     * CrossOrigin:必须满足spirng 4.2以上支持
     */
    @RequestMapping(value = "/addGoodsToCartList", method = RequestMethod.POST)
    public HttpResult addGoodsToCartList(Long itemId, Integer num,
                                         HttpServletRequest request, HttpServletResponse response) {

        try {
            /** 1、获取token里的用户信息，判断是否已登录 */
            User user = this.getUser(request);

            /** 2、查询购物车列表数据 */
            List<Cart> cartList = this.findCartList(request, response);

            /**3，添加购物车数据（把新的数据添加到原来的购物车列表中）*/
            cartList = cartService.addItemsToCartList(cartList, itemId, num);

            //4,判断用户此时是否登录
            if (user != null && user.getUsername() != null && !"".equals(user.getUsername())) {
                //登录状态，把购物车列表放入redis购物车
                cartService.addRedisCart(cartList, user.getId());
                return HttpResult.ok("购物车添加成功");
            } else {
                //未登录
                String serverName = request.getRequestURL().toString();
                Cookie cookie = new Cookie("111","222");
                cookie.setPath("/");
                cookie.setDomain("natapp1.cc");
//                cookie.setMaxAge(lifecycle);
                response.addCookie(cookie);
//                CookieUtils.setCookie(request,
//                        response,
//                        "cookie_cart",
//                        JSON.toJSONString(cartList),
//                        1728000000,
//                        true);
                // 未登录，把查询到的购物车信息返回给前端自己保存
                return HttpResult.ok(cartList);

            }

        }catch (Exception e) {
            e.printStackTrace();
            return HttpResult.error(HttpStatus.SC_FORBIDDEN,"添加购物车失败");
        }
    }

    @RequestMapping(value = "/updateOption", method = RequestMethod.POST)
    public HttpResult updateCartList(Long id, String type, Boolean bool, HttpServletRequest request, HttpServletResponse response) {

        /** 1、获取token里的用户信息，判断是否已登录 */
        User user = this.getUser(request);

        /** 查询cookie购物车 */
        List<Cart> cookieCartList = this.getCookieCart(request);

        /** 判断用户是否登录 */
        if (user!=null) {
            /** 获取redis购物车 */
            List<Cart> redisCartList = cartService.findRedisCartList(String.valueOf(user.getId()));
            List<Cart> newRedisCart = cartService.updateOption(redisCartList, id, type, bool);

            //登录状态，把购物车列表放入redis购物车
            cartService.addRedisCart(newRedisCart, user.getId());
        }else {
            // 未登录
            List<Cart> newCookieCart = cartService.updateOption(cookieCartList, id, type, bool);
            CookieUtils.setCookie(request,
                    response,
                    "cookie_cart",
                    JSON.toJSONString(newCookieCart),
                    1728000000,
                    true);


        }

        return HttpResult.ok();
    }

    @RequestMapping(value = "/updateCartList", method = RequestMethod.POST)
    public HttpResult updateCartList(Long itemId, Integer num, HttpServletRequest request, HttpServletResponse response) {

        /** 1、获取token里的用户信息，判断是否已登录 */
        User user = this.getUser(request);

        /** 查询cookie购物车 */
        List<Cart> cookieCartList = this.getCookieCart(request);

        List<Cart> newCartList = new ArrayList<>();
        /** 判断用户是否登录 */
        if (user!=null) {
            //登录状态
            /** 获取redis购物车 */
            List<Cart> redisCartList = cartService.findRedisCartList(String.valueOf(user.getId()));

            /** 对cookie购物车 做 增加或修改 */
            newCartList = cartService.addItemsToCartList(redisCartList, itemId, num);

            //登录状态，把购物车列表放入redis购物车
            cartService.addRedisCart(newCartList, user.getId());
        }else {
            // 未登录
            /** 对cookie购物车 做 增加或修改 */
            newCartList = cartService.addItemsToCartList(cookieCartList, itemId, num);

            CookieUtils.setCookie(request,
                    response,
                    "cookie_cart",
                    JSON.toJSONString(newCartList),
                    1728000000,
                    true);

        }

        return HttpResult.ok(newCartList);
    }

    @RequestMapping(value = "/getCartList", method = RequestMethod.POST)
    public HttpResult getCartList(HttpServletRequest request, HttpServletResponse response) {
        return HttpResult.ok(this.findCartList(request, response));
    }

    @RequestMapping(value = "/findCartList", method = RequestMethod.POST)
    public List<Cart> findCartList(HttpServletRequest request, HttpServletResponse response) {

        /** 1、获取token里的用户信息，判断是否已登录 */
        User user = this.getUser(request);

        /** 查询cookie购物车 */
        List<Cart> cookieCartList = this.getCookieCart(request);

        //判断用户是否登录
        if (user!=null) {
            //登录状态
            //查询redis购物车
            List<Cart> redisCartList = this.redisMergeCart(cookieCartList, user, request, response);

            return redisCartList;
        } else {
            //未登录
            return cookieCartList;
        }


    }

    /**
     * 解析请求对象的token得到用户信息
     * @param request
     * @return
     */
    public User getUser(HttpServletRequest request) {

        // 解析请求头中的token
        String userStr = request.getHeader("user");
        User user = null;
        if(userStr != null && !"".equals(userStr)) {
            user = JSONObject.parseObject(userStr, User.class);
        }
        return user;
    }

    public List<Cart> getCookieCart(HttpServletRequest request) {
        //查询cookie购物车
        String cookie_cart = CookieUtils.getCookieValue(request, "cookie_cart", true);

        //判断cookie购物车数据是否为空
        if (cookie_cart == null || "".equals(cookie_cart)) {
            cookie_cart = "[]";
        }
        //把cookie购物车转换成集合对象
        List<Cart> cookieCartList = JSON.parseArray(cookie_cart, Cart.class);
        return cookieCartList;
    }

    public List<Cart> redisMergeCart(List<Cart>cookieCartList, User user, HttpServletRequest request, HttpServletResponse response) {
        List<Cart> redisCartList = cartService.findRedisCartList(String.valueOf(user.getId()));

        //判断cookie购物车是否存在
        if (cookieCartList != null && cookieCartList.size() > 0) {
            //合并购物车
            //把cookie购物车列表数据合并到redis购物车列表
            redisCartList = cartService.mergeCart(redisCartList, cookieCartList);
//            System.out.println(redisCartList);
        }
        //添加到redis购物车
        cartService.addRedisCart(redisCartList, user.getId());
        CookieUtils.setCookie(request, response,
                "cookie_cart",
                "",
                0,
                true);
        return redisCartList;
    }

}
